<template>
  <Home :title="title" collectionName="kenny.bai" ref="root"></Home>

  <div v-for="(item, i) in list" :key="i" :ref="el => { if (el) divs[i] = el}">
    {{item}}
  </div>
</template>

<script>
import Home from '@/views/Home'
import { provide, ref, reactive, readonly, onMounted, onBeforeUpdate, watchEffect } from 'vue'

export default {
  data () {
    return {
      title: 'kenny.bai'
    }
  },
  components: {
    Home
  },
  mounted () {
    setInterval(() => {
      this.title = this.title + 'a'
      console.log(this.title)
    }, 3000)
  },
  setup (props) {
    // let reName = 'kenny.bai'
    // let reAge = 18
    // const reOtherInfo = {
    //   score: 100,
    //   sex: 'male'
    // }

    // 无法响应式更新
    // setInterval(() => {
    //   reName = reName + 'a'
    //   reAge = reAge + 1
    //   reOtherInfo.score = reOtherInfo.score + 1
    // }, 1000)

    const reName = ref('kenny.bai')
    const reAge = ref(18)
    const reOtherInfo = reactive({
      score: 100,
      sex: 'male'
    })

    const location = ref('North Pole')
    const updateLocation = () => {
      location.value = 'South Pole'
    }

    setInterval(() => {
      reName.value = reName.value + 'a'
      reAge.value = reAge.value + 1
      reOtherInfo.score = reOtherInfo.score + 1
    }, 1000)

    provide('name', readonly(reName))
    provide('age', reAge)
    provide('otherInfo', reOtherInfo)
    provide('updateLocation', updateLocation)

    const root = ref(null)

    onMounted(() => {
      // 如果 VNode 的 ref 键对应于渲染上下文中的 ref，则 VNode 的相应元素或组件实例将被分配给该 ref 的值
      console.log('root:', root.value)
    })

    const list = reactive([1, 2, 3])
    const divs = ref([])

    onBeforeUpdate(() => {
      divs.value = []
    })

    // 这个副作用在DOM更新之前运行， 因此， 模板引用还没有持有对元素的引用。第一次获取root.value为null，第二次可以获取到真实的root.value
    // 可以使用flush: 'post'，是的watchEffect在DOM更新后运行副作用
    watchEffect(() => {
      console.log('root 2:', root.value)
    }, {
      flush: 'post'
    })

    // 必须导出root，才能关联组件上的ref
    return {
      root,
      list,
      divs
    }
  }
}
</script>

<style lang="scss">
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;

  a {
    font-weight: bold;
    color: #2c3e50;

    &.router-link-exact-active {
      color: #42b983;
    }
  }
}
</style>
